<?php

class Shopping_Cart {
	var $cart_name;
	var $items;
	
	function __construct($name) {
		$this->cart_name = $name;
		if(isset($_SESSION [$this->cart_name])){
			$this->items = unserialize($_SESSION [$this->cart_name]);
		}
	}
	
	
	function addItem($menuId, $quantity){
		if(!is_null($this->items)){
			for($i=0; $i<count($this->items); $i++){
				if($this->items[$i]->menuId == $menuId){
					$this->items[$i]->addQuantity($quantity);
					$this->save();
					return;
				}
			}
		}
		$newMenuItem = new MenuItem($menuId, $quantity);
		$this->items[] = $newMenuItem;
		$this->save();
	}

	function removeItem($menuId){
		for($i=0; $i<count($this->items); $i++){
			if($this->items[$i]->menuId == $menuId){
				unset($this->items[$i]);
				$this->items = array_values($this->items);
				break;
			}
		}
		$this->save();
	}

	function updateQuantity($menuId, $quantity){
		for($i=0; $i<count($this->items); $i++){
			if($this->items[$i]->menuId == $menuId){
				$this->items[$i]->setQuantity($quantity);
				break;
			}
		}
		$this->save();
	}	
		
	function emptyCart(){
		$this->items = null;
		$this->save();
	}
	
	function save() {
		$_SESSION [$this->cart_name] = serialize($this->items);
	}
	
	function getInList(){
		$inStr = '';
		for($i=0; $i<count($this->items); $i++){
			if($i>0){
				$inStr = $inStr.',';
			}
			$inStr = $inStr.($this->items[$i]->getMenuId());
		}
		return $inStr;		
	}
	
	function getQuantityByMenuId($menuId){
		for($i=0; $i<count($this->items); $i++){
			if($this->items[$i]->menuId == $menuId){
				return $this->items[$i]->getQuantity();
			}
		}
	}
	
	function getAllQuantity(){
		$sumQuantity = 0;
		for($i=0; $i<count($this->items); $i++){
			$sumQuantity = $sumQuantity + $this->items[$i]->getQuantity();
		}
		return $sumQuantity;
	}
}
?>